package com.chianghao.auth.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.chianghao.auth.cache.model.resource.PathResource;
import com.chianghao.core.exception.ErrorInfo;
import com.chianghao.core.exception.HaoException;
import com.chianghao.core.utils.UrlAntUtils;

public class PathMatcherUtils {


	public static PathResource lookupWhiteListInfo(String url, Collection<PathResource> tagPathCollection) {
		if(tagPathCollection==null||tagPathCollection.size()==0) {
			return null;
		}
		MultiValueMap<String, PathResource> urlLookup = new LinkedMultiValueMap<>();
		for(PathResource white:tagPathCollection) {
			urlLookup.add(white.getUrl(), white);
		}
		List<PathResource> directPathMatches = urlLookup.get(url);
		if(directPathMatches==null) {
			directPathMatches = new ArrayList<PathResource>();
		}
		if(directPathMatches.size()==0) {
			for(PathResource white:tagPathCollection) {
				String  tagUrl = UrlAntUtils.getMatchingPattern(white.getUrl(),url);
				if(tagUrl==null) {
					continue;
				}
				if(tagUrl.equals(white.getUrl())) {
					directPathMatches.add(white);
				}
			}
		}
		if(directPathMatches.size()==1) {
			return directPathMatches.get(0);
		}else if(directPathMatches.size()==0){
			return null;
		}else if(directPathMatches.size()>1){
			return directPathMatches.get(0);
		}else {
			throw new HaoException(ErrorInfo.find_more_url);
		}
	}


}
